//
//  CK_MenuViewController.m
//  MenuDemo
//
//  Created by 陈凯 on 16/4/14.
//  Copyright © 2016年 鸥！陈凯. All rights reserved.
//

#import "CK_MenuViewController.h"
#import "UIImage+ImageEffects.h"
#import "LMAVManager.h"
#import "LMRadioListModel.h"
#import "LMDownLoadController.h"
#import "LMCollectController.h"


// 抽屉展开的程度
#define kMenuLeftWidth [UIScreen mainScreen].bounds.size.width * 0.7

@interface CK_MenuViewController ()<UITableViewDataSource, UITableViewDelegate>


///歌曲照片
@property (nonatomic, strong) UIImageView *songImgView;

@property (nonatomic, strong) UIButton *actionBtn;

@end

@implementation CK_MenuViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // 手势
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panMenuWithPanGesture:)];
    [self.view addGestureRecognizer:pan];
    

}
#pragma mark - 判断当前菜单是否展开

- (BOOL)isShowing {
    if (self.centerViewController.view.transform.tx > 0) {
        return YES;
    }
    return NO;
}


#pragma mark - 初始化方法
/*
 如果有左视图，就使用自己的，如果没有那就用这个里面自带的。
 建议自己从新写抽屉里面的视图
 */
static CK_MenuViewController *CK_menuVC = nil;
+ (instancetype)instanceWithLeftViewController:(UIViewController *)leftVC CenterViewController:(UIViewController *)centerVC {
    @synchronized(self) {
        if (!CK_menuVC) {
            
            CK_menuVC = [[CK_MenuViewController alloc]init];
            // 设置window的rootViewController
            [UIApplication sharedApplication].keyWindow.rootViewController = CK_menuVC;
            // 设置属性
            CK_menuVC.leftViewController = leftVC;
            CK_menuVC.centerViewController = centerVC;
            // 添加子视图控制器和子视图
            if (leftVC) {
                [CK_menuVC addChildViewController:leftVC];
                [CK_menuVC.view addSubview:leftVC.view];
            }else {
                [CK_menuVC setupLeftViewController];
            }
            if (centerVC) {
                [CK_menuVC addChildViewController:centerVC];
                [CK_menuVC.view addSubview:centerVC.view];
            }
        }
    }
    return CK_menuVC;
}


#pragma mark -  默认的菜单视图

- (void)setupLeftViewController {
    self.leftTableView = [[UITableView alloc]    initWithFrame:CGRectMake(-kMenuLeftWidth, 0, kMenuLeftWidth, self.view.frame.size.height) style:UITableViewStylePlain];
    // 设置数据源
    self.leftTableView.dataSource = self;
    // 代理
    self.leftTableView.delegate = self;
    UIImageView *backImageView = [[UIImageView alloc]initWithFrame:self.view.bounds];
    UIImage *image =[UIImage imageNamed:@"ba.jpg"];
    

    [backImageView setImage:[image applyTintEffectWithColor:[UIColor grayColor]]];
    self.leftTableView.backgroundView = backImageView;

    
    
    self.leftTableView.separatorStyle = UITableViewCellSelectionStyleNone;
    self.leftTableView.scrollEnabled = NO;
    [self.view addSubview:self.leftTableView];
}


#pragma mark - UITableViewDataSource

// 数据源代理方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
         return self.menuArray.count;
    }
    if (section == 1) {
    return self.menuArray2.count;
    }
    return 0;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *reuserID = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuserID];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuserID];
    }
    cell.backgroundColor = [UIColor clearColor];
    cell.textLabel.textColor = [UIColor whiteColor];
    
    [cell.textLabel setFont:[UIFont systemFontOfSize:22 weight:4]];
    if (indexPath.section ==0 ) {
        cell.textLabel.text = self.menuArray[indexPath.row];
    }
    if (indexPath.section == 1) {
    cell.textLabel.text = self.menuArray2[indexPath.row];
    }

    return cell;
}



// menuArray的setter方法
- (void)setMenuArray:(NSMutableArray *)menuArray {
    if (_menuArray != menuArray) {
        _menuArray  = nil;
        _menuArray  = menuArray;
        [self.leftTableView reloadData];
    }
}
-(void)setMenuArray2:(NSMutableArray *)menuArray2{
    if (_menuArray2 != menuArray2) {
        _menuArray2  = nil;
        _menuArray2 = menuArray2;
        [self.leftTableView reloadData];
    }
}


#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // 取消选中状态
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    // 代理 传值
    if ([self.menuDelegate respondsToSelector:@selector(didClickMenuIndex:Title:)]) {
        if (indexPath.section == 0) {
    
        [self.menuDelegate didClickMenuIndex:indexPath.row Title:self.menuArray[indexPath.row]];
            
        }else{
        [self.menuDelegate didClickMenuIndex:indexPath.row Title:self.menuArray2[indexPath.row]];
        }
    }
    // 关闭抽屉
    [self hideLeftViewController];
}


#pragma mark -  获取抽屉方法

+ (instancetype)getMenuViewController {
    return CK_menuVC;
}


#pragma mark - 左侧菜单

// 展示左侧菜单
- (void)showLeftViewController {
    // 动画展开
    [self showLeftViewController:0.7];
}
- (void)showLeftViewController:(CGFloat)duration{
    [UIView animateWithDuration:duration animations:^{
//        在打开抽屉时 把主视图的交互关了
        [self.centerViewController.view setUserInteractionEnabled:NO];
        self.centerViewController.view.transform = CGAffineTransformMakeTranslation(kMenuLeftWidth, 0);
        self.leftViewController.view.transform = CGAffineTransformMakeTranslation(kMenuLeftWidth, 0);
        self.leftTableView.transform = CGAffineTransformMakeTranslation(kMenuLeftWidth, 0);
    }];
}
// 关闭左侧菜单
- (void)hideLeftViewController {
    [self hideLeftViewController:0.7];
}
- (void)hideLeftViewController:(CGFloat)duration {
    //        在关闭抽屉时 把主视图的交互开了
    [self.centerViewController.view setUserInteractionEnabled:YES];
    // 动画关闭
    [UIView animateWithDuration:duration animations:^{
        self.centerViewController.view.transform = CGAffineTransformMakeTranslation(0, 0);
        self.leftViewController.view.transform = CGAffineTransformMakeTranslation(0, 0);
        self.leftTableView.transform = CGAffineTransformMakeTranslation(0, 0);
    }];
}
//加触摸事件，
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self hideLeftViewController];
}

#pragma mark -  手势控制抽屉

// 静态变量保存初始状态
static CGPoint begin;
static CGAffineTransform transform;
- (void)panMenuWithPanGesture:(UIPanGestureRecognizer *)pan {
    // 位移量
    CGPoint translatePoint = CGPointZero;
    // 开始手势时的位置
    if (pan.state == UIGestureRecognizerStateBegan) {
        begin = [pan locationInView:self.view];
        transform = self.centerViewController.view.transform;
    }
    // 手势过程中的位置
    if (pan.state == UIGestureRecognizerStateChanged) {
        CGPoint end = [pan locationInView:self.view];
        translatePoint = CGPointMake(end.x - begin.x, 0);
    }
    // 手势结束时的位置
    if (pan.state == UIGestureRecognizerStateCancelled || pan.state == UIGestureRecognizerStateEnded) {
        if ([pan velocityInView:self.view].x > 0) {
            // 动画设置动画时长
            [self showLeftViewController:0.13];
        }else {
            [self hideLeftViewController:0.13];
        }
        return;
    }
    // 手势过程中，对视图进行位移
    if(self.centerViewController.view.transform.tx >= 0 && self.centerViewController.view.transform.tx <= kMenuLeftWidth) {
        self.centerViewController.view.transform = CGAffineTransformTranslate(transform, translatePoint.x, 0);
        self.leftViewController.view.transform = CGAffineTransformTranslate(transform,translatePoint.x, 0);
        self.leftTableView.transform = CGAffineTransformTranslate(transform, translatePoint.x, 0);
    }
}


#pragma mark - tableView HeaderView

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 2) {
        return 200;
    }
    return 55;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 200;
    }
    return 10;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section == 1) {
        return 140;
    }
    return 10;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
     UIView *view= [[UIView alloc]initWithFrame:CGRectZero];
    if (section == 0) {
        view.frame= CGRectMake(0, 0, kMenuLeftWidth, 150);
        self.imgView = [[UIImageView alloc]initWithFrame:CGRectMake(10, 70, 100, 100)];
        self.imgView.contentMode = UIViewContentModeScaleAspectFit;
        self.imgView.layer.cornerRadius = 50;
        self.imgView.clipsToBounds = YES;
        if ([UserInfoManager shareManager].auth == nil) {
            self.imgView.image = [UIImage imageNamed:@"2"];
        }
        
        
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(120, 111, self.view.frame.size.width * 0.7 - self.imgView.frame.size.width - 20, 40);
        self.nameBtn = btn;

        [btn showsTouchWhenHighlighted];
        if ([UserInfoManager shareManager].auth == nil) {
        [btn setTitle:@"未登录" forState:UIControlStateNormal];
        }
        [btn addTarget:self action:@selector(LoginAction) forControlEvents:UIControlEventTouchUpInside];

        [view addSubview:btn];
        [view addSubview:self.imgView];
        

    }
    
  return view;
}

- (void)showDownloadListAction{
       if ([UserInfoManager shareManager].auth) {
           LMDownLoadController *downVC = [[LMDownLoadController alloc]init];
           [self presentViewController:downVC animated:YES completion:nil];
    }else{
//        NSLog(@"没有登录");
        UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"提示" message:@"没有登录，马上去登陆" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *yesAction = [UIAlertAction actionWithTitle:@"YES" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            UIStoryboard *storyboad = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            UIViewController *loginVC = [storyboad instantiateViewControllerWithIdentifier:@"Login"];
            [self presentViewController:loginVC animated:YES completion:nil];
        }];
        [alertC addAction:yesAction];
        
        UIAlertAction *noAction = [UIAlertAction actionWithTitle:@"NO" style:UIAlertActionStyleDefault handler:nil];
        [alertC addAction:noAction];
        
        [self presentViewController:alertC animated:YES completion:nil];
    }

}


#pragma mark - 登录

- (void)LoginAction{
    if ([UserInfoManager shareManager].auth) {
//        NSLog(@"已经登录了");
        return;
    }else{
    UIStoryboard *storyboad = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    UIViewController *loginVC = [storyboad instantiateViewControllerWithIdentifier:@"Login"];
    [self presentViewController:loginVC animated:YES completion:nil];
    }
}

//#warning 没做出来 可以放弃

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *view= [[UIView alloc]initWithFrame:CGRectZero];
    if (section == 1) {
        
        self.songImgView  =[[UIImageView alloc]initWithFrame:CGRectMake(30, 50, 60, 60)] ;
        self.songImgView .backgroundColor = [UIColor clearColor];
        
        LMRadioListModel *model = [[LMAVManager shareManager]itemArray][arc4random()% 3 + 1];
        [self.songImgView sd_setImageWithURL:[NSURL URLWithString:model.coverimg]];
        self.songImgView.image = [UIImage imageNamed:@"2"];
        [view addSubview:self.songImgView ];
        
        UILabel *songLabel = [[UILabel alloc]initWithFrame:CGRectMake(110, 50, 80, 50)];
        songLabel.text = @"歌曲名";
        songLabel.textColor = [UIColor whiteColor];
        songLabel.font = [UIFont systemFontOfSize:18 weight:4];

        [view addSubview:songLabel];
        
        UILabel *authorLabel = [[UILabel alloc]initWithFrame:CGRectMake(110, 80, 80, 50)];
        authorLabel.text = @"作者";
        authorLabel.textColor = [UIColor whiteColor];
        authorLabel.font = [UIFont systemFontOfSize:14 weight:2];
   
        [view addSubview:authorLabel];
        
        UIButton *actionBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        actionBtn.frame = CGRectMake(kMenuLeftWidth - 66, 60, 50, 50);
        [actionBtn setImage:[UIImage imageNamed:@"开始"] forState:UIControlStateNormal];
        [actionBtn addTarget:self action:@selector(PlayAction) forControlEvents:UIControlEventTouchUpOutside];
        self.actionBtn = actionBtn;
        [view addSubview:actionBtn];
     
        
    }
  return view;
}

- (void)PlayAction{
        UIImage *unSelectImg = [UIImage imageNamed:@"开始"];
        UIImage *selectImg = [UIImage imageNamed:@"结束"];
    if ([LMAVManager shareManager].player.rate == 0) {
        [[LMAVManager shareManager]play];
        [self.actionBtn setImage:selectImg forState:UIControlStateNormal];
    }else{
        [[LMAVManager shareManager]pause];
        [self.actionBtn setImage:unSelectImg forState:UIControlStateNormal];
        
    }
}










@end
